<template>
  <div class="page login-page col center-span middle-span">
    <div class="login-container">
      <div class="title">用户登录</div>
      <Form ref="loginForm" :model="loginModel" :rules="loginRule" class="login-form">
        <Form-item prop="username">
          <Input type="text" v-model="loginModel.username" placeholder="用户名">
          <Icon type="ios-body" slot="prepend"></Icon>
          </Input>
        </Form-item>
        <Form-item prop="password">
          <Input type="password" v-model="loginModel.password" placeholder="密码">
          <Icon type="ios-locked-outline" slot="prepend"></Icon>
          </Input>
        </Form-item>
        <Form-item>
          <Button class="login-button" type="primary" @click="loginHandle">登录</Button>
          <Button class="login-button" type="primary" @click="$router.push('register')">注册</Button>
        </Form-item>
      </Form>
    </div>
  </div>
</template>
<script>
  import { mapMutations } from 'vuex'
  import { Users } from '/imports/collections'
  export default {
    meteor: {
      $subscribe: {
        'users.login' () {
          return [{
            username: this.loginModel.username,
            password: this.loginModel.password
          }]
        }
      }
    },
    data () {
      return {
        loginModel: {
          username: '',
          password: ''
        },
        loginRule: {
          username: [
            { required: true, message: '请填写用户名', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请填写密码', trigger: 'blur' },
            { type: 'string', min: 5, message: '密码长度不能小于6位', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      ...mapMutations([
        'updateUserData'
      ]),
      loginHandle () {
        this.$refs.loginForm.validate((valid) => {
          // 验证失败
          if (!valid) { return }
  
          // 查找用户信息
          let user = Users.findOne()
          if (user) {
            this.updateUserData(user)
            this.$router.push('project-list')
          } else {
            this.$Message.error('用户名或密码错误')
          }
        })
      }
    },
    mounted () {
      console.log(this.$store.state)
    }
  }
</script>
<style lang="less" scoped>
  @import "~imports/assets/styles/theme.less";

  .login-form {
    width: 300px;
  }

  .login-button {
    width: 120px;
  }

  .login-page {
    background-color: @COLOR5;
  }

  .title {
    font-size: 20px;
    margin: 20px;
    color: @COLOR1;
  }

</style>
